package br.mikhas.util;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Util methods to help creating collections
 * 
 * @author Mikhail Domanoski
 * 
 */
public class CollectionUtils {

	/**
	 * Creates a list from an array of values
	 * 
	 * @param <T>
	 *            The type of the elements on the list
	 * @param values
	 *            The values to be added on the list
	 * @return A list with all values on the array
	 */
	public static <T> List<T> list(T... values) {
		return Arrays.asList(values);
	}

	/**
	 * Creates a set with the vallues passed on the array
	 * 
	 * @param <T>
	 *            The type of the elements on the array
	 * @param values
	 *            The values to be added on the set
	 * @return The set
	 */
	public static <T> Set<T> set(T... values) {
		Set<T> set = new HashSet<T>(values.length);

		for (int i = 0; i < values.length; i++)
			set.add(values[i]);

		return set;
	}

	/**
	 * Creates a map from an array of key-value entries
	 * 
	 * @param <K>
	 *            The type of the key of the pair
	 * @param <V>
	 *            The type of the value element
	 * @param args
	 *            an array with even number of values which should represent a
	 *            key-value pair.
	 *            <p>
	 *            Ex.: map(key1, value1, key2, value2, key3, value3, ...)
	 * @return A map with the entries
	 */
	@SuppressWarnings("unchecked")
	public static <K, V> Map<K, V> map(Object... args) {

		if (args.length % 2 != 0)
			throw new IllegalArgumentException(
					"Illegal number of key-value pair entries");

		Map<K, V> map = new HashMap<K, V>(args.length / 2);

		for (int i = 0; i < args.length; i = i + 2) {
			K key = (K) args[i];
			V value = (V) args[i + 1];
			map.put(key, value);
		}

		return map;

	}

}
